package com.mbc.web.common.client.ui;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.mbc.common.data.UserData;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.shared.HttpStatus;

public class FrmLogin extends Composite {

	private static FrmLoginUiBinder uiBinder = GWT
			.create(FrmLoginUiBinder.class);
	@UiField MButton btnLogin;
	@UiField TextBox txtLoginId;
	@UiField PasswordTextBox txtPassword;
	@UiField ListBox listCompany;
	@UiField CheckBox chkRemember;
	@UiField Anchor anchorForgetPwd;

	public static String loginId;
	public static String password;
	public static String dsName;
	
	interface FrmLoginUiBinder extends UiBinder<Widget, FrmLogin> {
	}

	public FrmLogin() {
		initWidget(uiBinder.createAndBindUi(this));
		FormLoad();
	}
		
	private boolean isValid()
	{
		if(txtLoginId.getText().equals("")){
			txtLoginId.setFocus(true);
			showMessage("Invalid Login Id.");
			return false;
		}
		if(txtPassword.getText().equals("")){
			txtPassword.setFocus(true);
			showMessage("Invalid password.");
			return false;
		}
		if(listCompany.getSelectedIndex() == -1){
			listCompany.setFocus(true);
			showMessage("Invalid company.");
			return false;
		}
		return true;
	}

	private void FormLoad()
	{
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				removeDefaultCSS();
				String l_login = Cookies.getCookie("login");
				if(l_login == null)
					txtLoginId.setFocus(true);
				else{
					txtLoginId.setText(l_login);
					txtPassword.setFocus(true);
					chkRemember.setValue(true);
				}
			}
		});
		CommonControllerMgr.getDSNames(getDSNamesCallback());
	}
	
	@UiHandler("btnLogin")
	void onBtnLoginClick(ClickEvent event) {
		if(chkRemember.getValue()){
			Cookies.setCookie("login", txtLoginId.getText());
		}
		clearMessage();
		if(isValid())
		{
			FrmLogin.loginId = txtLoginId.getText();
			FrmLogin.password = txtPassword.getText();
			FrmLogin.dsName = listCompany.getValue(listCompany.getSelectedIndex());
			ViewUtils.closeMessageBox();
			ViewUtils.startAjaxLoader("Logging in...");
			if(ClientSingleton.loginClickHandler == null){
				CommonControllerMgr.login(txtLoginId.getText(), txtPassword.getText(), FrmLogin.dsName, loginCallback());
			} else {
				ClientSingleton.loginClickHandler.onClick(event);
			}
		}
	}
	
	private AsyncCallback<UserData> loginCallback()
	{
		return new AsyncCallback<UserData>() {
			
			@Override
			public void onSuccess(UserData result) {
				ViewUtils.stopAjaxLoader();
				if(result.getReponseStatus() == HttpStatus.OK)
				{
					ClientSingleton.setMyanmarCurrencyName(result.getMyanmarCurrencyName());
					ClientSingleton.setMyanmarDecName(result.getMyanmarDecName());
					ClientSingleton.setMyanmarNumbers(result.getMyanmarNumbers());
					ClientSingleton.setMyanmarNumberValues(result.getMyanmarNumberValues());
					ClientSingleton.appItemList = result.getAppItemList();
					ClientSingleton.showMainTags();
					ClientSingleton.setLoginId(FrmLogin.loginId);
					setUserInfo(result.getUserName(), result.getBranchName());
				}
				else if(result.getReponseStatus() == HttpStatus.UNAUTHORIZED)
				{
					showMessage("Invalid Login Id and Password.");
				}
				else if(result.getReponseStatus() == HttpStatus.getStatusExtension(HttpStatus.UNAUTHORIZED, 1)){
					showMessage("This user is currently online.");
				}
				else if(result.getReponseStatus() == HttpStatus.INTERNAL_SERVER_ERROR)
				{
					showMessage(CommonMessage.internal_server_error_message);
				}
				FrmLogin.loginId = "";
				FrmLogin.password = "";
				FrmLogin.dsName = "";
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private AsyncCallback<List<String[]>> getDSNamesCallback()
	{
		return new AsyncCallback<List<String[]>>() {
			
			@Override
			public void onSuccess(List<String[]> result) {
				for (String[] l_ds : result) {
					listCompany.addItem(l_ds[1], l_ds[0]);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	private native void setUserInfo(String userName, String branchName)/*-{
		$wnd.$("#spanUserName").text(userName);
		$wnd.$("#spanBranchName").text(branchName);
	}-*/;
	
	private native void clearMessage()/*-{
		$wnd.$("#msgDiv").hide();
		$wnd.$("#messagelbl").text("");
	}-*/;
	
	public static native void showMessage(String message)/*-{
		$wnd.$("#msgDiv").show();
		$wnd.$("#messagelbl").text(message);
	}-*/;
	
	private native void removeDefaultCSS()/*-{
		$wnd.$("link").each(function(){
		if($wnd.$(this).attr("href").indexOf("clean.css") > -1)
            $wnd.$(this).remove();
		});
	}-*/;
}
